package com.etung.iot.demo.utils;

import com.etung.iot.demo.constant.CommonConstant;
import com.etung.iot.demo.modles.ConditionStorageEntity;
import com.etung.iot.demo.modles.RealData;
import com.etung.iot.demo.storage.constorage.OperEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class StorageUtil {
    @Autowired
    private RedisUtil redisUtil;
    public  boolean scaleTypeJudge(BigDecimal monitorValue, ConditionStorageEntity conditionStorageEntity) {
        BigDecimal targetValue = BigDecimalUtil.getBigDecimal(conditionStorageEntity.getTargetValue());
        return compare(conditionStorageEntity.getOper(), monitorValue, targetValue);
    }

    public boolean varTypeJudge(String imei, BigDecimal monitorValue, ConditionStorageEntity conditionStorageEntity) {
        Integer targetVarId = conditionStorageEntity.getTargetVarId();
        String cacheKey = CommonConstant.REAL_DATA_CACHE_PREFIX + imei + "_" + targetVarId;
        RealData realData = (RealData) redisUtil.get(cacheKey);
        if(realData == null || StringUtils.isEmpty(realData.getValue()))  return false;
        BigDecimal targetDecimalValue = BigDecimalUtil.getBigDecimal(realData.getValue());
        return compare(conditionStorageEntity.getOper(), monitorValue, targetDecimalValue);
    }

    public boolean compare(int symbol, BigDecimal src, BigDecimal target) {
        if (symbol == OperEnum.EQUAL.getValue()) {
            return src.compareTo(target) == 0;
        } else if (symbol == OperEnum.GT.getValue()) {
            return src.compareTo(target) > 0;
        } else if (symbol == OperEnum.GT_EQUAL.getValue()) {
            return src.compareTo(target) >= 0;
        } else if (symbol == OperEnum.LT.getValue()) {
            return src.compareTo(target) < 0;
        } else if (symbol == OperEnum.LT_EQUAL.getValue()) {
            return src.compareTo(target) < 0;
        } else if (symbol == OperEnum.NOT_EQUAL.getValue()) {
            return src.compareTo(target) != 0;
        }
        return false;
    }
}
